﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyDesktopPetDemo
{
	class LaunchDest
	{
		public string Name { get; set; }
		public string Cmd { get; set; }

		public LaunchDest(string name, string cmd)
		{
			Name = name;
			Cmd = cmd;
		}

		public void Launch()
		{
			try
			{
				System.Diagnostics.Process p = new Process();
				p.StartInfo.UseShellExecute = true;
				p.StartInfo.FileName = Cmd;
				p.Start();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		public override string ToString()
		{
			return Name;
		}
	}

	class LaunchpadService
	{
		const string configFile = "launchpad_path_config.txt";
		public static List<LaunchDest> Dests { get; private set; } = new();

		public static void ChangePath(string path)
		{
			if (string.IsNullOrEmpty(path)) return;
			using StreamWriter writer = new(configFile);
			writer.Write(path);
			Init();
		}

		public static void Init()
		{
			string path = "C:/Launchpad";
			
			if (File.Exists(configFile))
			{
				string newPath = File.ReadAllText(configFile).Trim();
				if (!string.IsNullOrWhiteSpace(newPath)) path = newPath;
				else ChangePath(path);
			}
			else
			{
				ChangePath(path);
			}

			try
			{
				if (!Directory.Exists(path))
				{
					Directory.CreateDirectory(path);
				}

				List<LaunchDest> dests = new();
				string[] files = Directory.GetFiles(path);
				foreach (string file in files)
				{
					dests.Add(new(Path.GetFileNameWithoutExtension(file), file));
				}
				Dests = dests;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		public static List<LaunchDest> Filter(string keyword)
		{
			List<LaunchDest> ret = new();
			foreach (var dest in Dests)
			{
				if (dest.Name.Contains(keyword))
				{
					ret.Add(dest);
				}
			}
			return ret;
		}

		public static void LaunchIfExists(string keyword)
		{
			LaunchDest? dest = Filter(keyword).FirstOrDefault();
			dest?.Launch();
		}
	}
}
